package com.sk.cardeal.act.home.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.PartsAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.dialog.BuyNextDialogFragment;
import com.sk.cardeal.entity.Parts;
import com.sk.cardeal.entity.PartsBean;
import com.sk.cardeal.entity.PartsBrandBean;
import com.sk.cardeal.entity.PartsListBean;
import com.sk.cardeal.entity.PartsSelectEntity;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.utils.UIUtils;
import com.sk.cardeal.view.EasyLoadingMoreView;
import com.sk.cardeal.view.FlowLayout;
import com.sk.cardeal.view.TitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/12/25.
 */

public class ChoosePartsActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener, CompoundButton.OnCheckedChangeListener, HandleDataCallBack, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.kind_ryc)
    RadioGroup kindRyc;
    @BindView(R.id.parts_ryc)
    RecyclerView partsRyc;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.apply_form)
    TextView applyForm;
    @BindView(R.id.title_view)
    TitleView titleView;

    ArrayList<PartsListBean.ResultListBean> partsList;
    @BindView(R.id.brand)
    TextView brand;
    @BindView(R.id.brand_ll)
    FlowLayout brandLl;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.reset)
    TextView reset;
    @BindView(R.id.sure_action)
    TextView sureAction;
    @BindView(R.id.dl_layout)
    DrawerLayout dlLayout;
    @BindView(R.id.sort)
    LinearLayout sort;
    @BindView(R.id.filter)
    TextView filter;
    @BindView(R.id.quality_flow)
    FlowLayout qualityFlow;
    @BindView(R.id.filter_ll)
    LinearLayout filterLl;
    @BindView(R.id.filter_group)
    RadioGroup filterGroup;
    @BindView(R.id.sort_img)
    ImageView sortImg;
    @BindView(R.id.com_sort)
    RadioButton comSort;
    @BindView(R.id.up_sort)
    RadioButton upSort;
    @BindView(R.id.down_sort)
    RadioButton downSort;
    private PartsSelectEntity partsSelectEntity;
    private int page = 0;
    private List<Parts> allDataList = new ArrayList<>();
    PartsAdapter adapter;
    private LoadingDialog loadingDialog;
    private String typeId = "";
    private int sortType = 0;
    private boolean isLoadMore = false;
    private List<Parts> selectParts = new ArrayList<>();
    private List<RadioButton> radioButtons = new ArrayList<>();

    private List<CheckBox> qualityList = new ArrayList<>();
    private List<CheckBox> brandCheckList = new ArrayList<>();

    private List<CheckBox> selectBrand = new ArrayList<>();
    private List<CheckBox> selectQuality = new ArrayList<>();

    private boolean isOpen = false;

    private boolean isReset = false;

    @Override
    protected int getContentView() {
        return R.layout.activity_choose_parts;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initAnimations();
        comSort.setChecked(true);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        titleView.setMyCallBack(this);
        partsList = getIntent().getParcelableArrayListExtra("data");
        List<Parts> selectData = getIntent().getParcelableArrayListExtra("select");
        selectParts.addAll(selectData);
        tvTip.setText("已选择" + caculateTotal() + "件商品");
        typeId = getIntent().getStringExtra("type");
        partsSelectEntity = new PartsSelectEntity();

        for (PartsListBean.ResultListBean bean : partsList) {
            RadioButton radioButton = (RadioButton) LayoutInflater.from(mContext).inflate(R.layout.item_kind, kindRyc, false);
            radioButton.setTag(bean);
            radioButton.setText(bean.getPartsName());
            kindRyc.addView(radioButton);
            radioButtons.add(radioButton);
            radioButton.setOnCheckedChangeListener(this);
        }

        partsRyc.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new PartsAdapter(R.layout.item_choose_parts, allDataList);
        partsRyc.setAdapter(adapter);
        EasyLoadingMoreView loadMoreView = new EasyLoadingMoreView();
        adapter.setLoadMoreView(loadMoreView);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnItemClickListener(this);
        adapter.setOnLoadMoreListener(this, partsRyc);
        radioButtons.get(0).setChecked(true);

        initQualityFlow();
    }


    private void initQualityFlow() {
        String[] strings = new String[]{"原厂件", "品牌件", "改装件", "自制件", "修复件", "拆车件"};
        for (int i = 0; i < strings.length; i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_filter_check_box, qualityFlow, false);
            CheckBox checkBox = view.findViewById(R.id.original);
            checkBox.setTag(String.valueOf(i + 1));
            checkBox.setText(strings[i]);
            qualityList.add(checkBox);
            qualityFlow.addView(view);
        }

        for (int i = 0; i < qualityList.size(); i++) {
            final int finalI = i;
            qualityList.get(i).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        selectQuality.add(qualityList.get(finalI));
                        if (!isReset) {
                            doRefresh();
                        }

                    } else {
                        selectQuality.remove(qualityList.get(finalI));
                        if (!isReset) {
                            doRefresh();
                        }
                    }
                }
            });
        }
    }

    private void doRefresh() {

        StringBuilder sb = new StringBuilder();
        if (selectQuality.size() > 0) {
            for (int i = 0; i < selectQuality.size(); i++) {
                String tag = (String) selectQuality.get(i).getTag();
                if (i == selectQuality.size() - 1) {
                    sb.append(tag);
                } else {
                    sb.append(tag).append(",");
                }
            }
        } else {
            sb.append("-1");
        }
        Log.v("doRefresh", sb.toString());
        loadingDialog.show();
        partsSelectEntity.setQuality(sb.toString());
        allDataList.clear();
        page = 1;
        AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);
    }


    //品牌筛选
    private void setPartsBrand(List<PartsBrandBean.ResultListBean> partsBrandLsit) {
        brandLl.removeAllViews();
        ;
        for (int i = 0; i < partsBrandLsit.size(); i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_filter_check_box, brandLl, false);
            CheckBox checkBox = view.findViewById(R.id.original);
            checkBox.setTag(partsBrandLsit.get(i).getBrandCode());
            checkBox.setText(partsBrandLsit.get(i).getBrandName());
            brandCheckList.add(checkBox);
            brandLl.addView(view);
        }


        for (int i = 0; i < brandCheckList.size(); i++) {
            final int finalI = i;
            brandCheckList.get(i).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        selectBrand.add(brandCheckList.get(finalI));
                        doBrandRefresh();

                    } else {
                        selectBrand.remove(brandCheckList.get(finalI));
                        doBrandRefresh();
                    }
                }
            });
        }
    }

    //品牌筛选
    private void doBrandRefresh() {
        StringBuilder sb = new StringBuilder();
        if (selectBrand.size() > 0) {
            for (int i = 0; i < selectBrand.size(); i++) {
                String tag = (String) selectBrand.get(i).getTag();
                if (i == selectBrand.size() - 1) {
                    sb.append(tag);
                } else {
                    sb.append(tag).append(",");
                }
            }
        } else {
            sb.append("-1");
        }
        Log.v("doRefresh", sb.toString());
        loadingDialog.show();
        partsSelectEntity.setBrand(sb.toString());
        allDataList.clear();
        page = 1;
        AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.add:
                int count = allDataList.get(position).getSelectCount();
                count++;
                allDataList.get(position).setSelectCount(count);
                adapter.notifyItemChanged(position);
                addSelect(allDataList.get(position));

                break;
            case R.id.reduce:
                int count1 = allDataList.get(position).getSelectCount();
                if (count1 > 0) {
                    count1--;
                    allDataList.get(position).setSelectCount(count1);
                    adapter.notifyItemChanged(position);
                    reduceSelect(allDataList.get(position));
                }
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isChecked) {
            PartsListBean.ResultListBean dataBean = (PartsListBean.ResultListBean) buttonView.getTag();
            loadingDialog.show();
            page = 0;
            allDataList.clear();
            partsSelectEntity.setPage(page);
            partsSelectEntity.setCategoryId(dataBean.getId());
            partsSelectEntity.setTypeId(typeId);
            partsSelectEntity.setSortType(sortType);
            partsSelectEntity.setCompanyId(MyUtils.getUser(mContext).getCompanyId());
            AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);
            AppApi.getPartsBrand(typeId, dataBean.getId(), ChoosePartsActivity.this, 2, ChoosePartsActivity.this);
        }


    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 1:
                if (isReset) {
                    isReset = false;
                }
                PartsBean partsBean = JSON.parseObject(result, PartsBean.class);
                List<Parts> dataBeanList = partsBean.getResultList();
                for (int i = 0; i < dataBeanList.size(); i++) {
                    for (int j = 0; j < selectParts.size(); j++) {
                        if (dataBeanList.get(i).getWarehousePartsId().equals(selectParts.get(j).getWarehousePartsId())) {
                            dataBeanList.get(i).setSelectCount(selectParts.get(j).getSelectCount());
                            break;
                        }
                    }
                }
                allDataList.addAll(dataBeanList);
                if (allDataList.size() < 10) {
                    adapter.setEnableLoadMore(false);
                } else {
                    adapter.setEnableLoadMore(true);
                }
                if (isLoadMore) {
                    adapter.loadMoreComplete();
                    if (dataBeanList.size() == 0) {
                        adapter.loadMoreEnd();
                    }
                    isLoadMore = false;
                }
                adapter.notifyDataSetChanged();

                break;
            case 2:
                PartsBrandBean partsBrandBean = JSON.parseObject(result, PartsBrandBean.class);
                List<PartsBrandBean.ResultListBean> listBeans = partsBrandBean.getResultList();
                setPartsBrand(listBeans);
                break;
        }


    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onLoadMoreRequested() {
        isLoadMore = true;
        page++;
        partsSelectEntity.setPage(page);
        AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);
    }

    private void addSelect(Parts parts) {

        Parts newPart = new Parts();
        newPart.setCount(parts.getCount());
        newPart.setGoodsCode(parts.getGoodsCode());
        newPart.setName(parts.getName());
        newPart.setPicUrl(parts.getPicUrl());
        newPart.setPartsSelfCode(parts.getPartsSelfCode());
        newPart.setPrice(parts.getPrice());
        newPart.setQuality(parts.getQuality());
        newPart.setVin(parts.getVin());
        newPart.setWarehousePartsId(parts.getWarehousePartsId());
        newPart.setType(parts.getType());
        newPart.setSelectCount(1);
        if (selectParts.size() == 0) {
            selectParts.add(newPart);
        } else {
            boolean isSelect = false;
            for (int i = 0; i < selectParts.size(); i++) {
                Parts bean = selectParts.get(i);
                if (parts.getWarehousePartsId().equals(bean.getWarehousePartsId())) {
                    isSelect = true;
                    int count = bean.getSelectCount();
                    count++;
                    bean.setSelectCount(count);
                    break;
                }
            }

            if (!isSelect) {
                selectParts.add(newPart);
            }
        }
        tvTip.setText("已选择" + caculateTotal() + "件商品");
    }

    private void reduceSelect(Parts parts) {

        Parts newPart = new Parts();
        newPart.setCount(parts.getCount());
        newPart.setGoodsCode(parts.getGoodsCode());
        newPart.setName(parts.getName());
        newPart.setPicUrl(parts.getPicUrl());
        newPart.setPartsSelfCode(parts.getPartsSelfCode());
        newPart.setPrice(parts.getPrice());
        newPart.setQuality(parts.getQuality());
        newPart.setVin(parts.getVin());
        newPart.setWarehousePartsId(parts.getWarehousePartsId());
        newPart.setType(parts.getType());
        newPart.setSelectCount(1);

        if (selectParts.size() == 0) {
            Toast.makeText(mContext, "您未选中任何商品！", Toast.LENGTH_SHORT).show();
        } else {
            for (int i = 0; i < selectParts.size(); i++) {
                Parts bean = selectParts.get(i);
                if (parts.getWarehousePartsId().equals(bean.getWarehousePartsId())) {
                    int count = bean.getSelectCount();
                    count--;
                    bean.setSelectCount(count);
                    if (count == 0) {
                        selectParts.remove(i);
                    }
                    break;
                }
            }
        }
        tvTip.setText("已选择" + caculateTotal() + "件商品");
    }

    @OnClick({R.id.tv_tip, R.id.apply_form, R.id.sort, R.id.filter, R.id.reset, R.id.com_sort, R.id.up_sort, R.id.down_sort, R.id.sure_action})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_tip:
                if (selectParts.size() > 0) {
                    BuyNextDialogFragment buyNextDialogFragment = new BuyNextDialogFragment();
                    buyNextDialogFragment.setMyCallBack(ChoosePartsActivity.this);
                    buyNextDialogFragment.show(getFragmentManager(), "goods");
                } else {
                    SnackUtils.showError(mRootView, "您尚未选择任何商品！");
                }

                break;
            case R.id.apply_form:
                if (selectParts.size() > 0) {
                    Intent intent = new Intent();
                    intent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) selectParts);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    SnackUtils.showError(mRootView, "您尚未选择任何商品！");
                }

                break;
            case R.id.sort:

                if (isOpen) {
                    closeSort();
                } else {
                    openSort();
                }

                break;
            case R.id.filter:
                dlLayout.openDrawer(GravityCompat.END);
                break;
            case R.id.reset:

                isReset = true;

                for (CheckBox checkBox : brandCheckList) {
                    checkBox.setChecked(false);
                }
                for (CheckBox checkBox : qualityList) {
                    checkBox.setChecked(false);
                }

                loadingDialog.show();
                partsSelectEntity.setBrand("-1");
                partsSelectEntity.setQuality("-1");
                allDataList.clear();
                page = 1;
                AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);

                break;

            case R.id.com_sort:
                closeSort();
                if (comSort.isChecked()) {
                    page = 1;
                    allDataList.clear();
                    partsSelectEntity.setSortType(0);
                    loadingDialog.show();
                    AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);
                }
                break;
            case R.id.up_sort:
                closeSort();
                if (upSort.isChecked()) {
                    page = 1;
                    allDataList.clear();
                    partsSelectEntity.setSortType(1);
                    loadingDialog.show();
                    AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);
                }
                break;
            case R.id.down_sort:
                closeSort();
                if (downSort.isChecked()) {
                    page = 1;
                    allDataList.clear();
                    partsSelectEntity.setSortType(2);
                    loadingDialog.show();
                    AppApi.getPartsList(partsSelectEntity, ChoosePartsActivity.this, 1, ChoosePartsActivity.this);
                }
                break;
            case R.id.sure_action:
                dlLayout.closeDrawer(GravityCompat.END);
                break;
        }
    }

    @Override
    public void doChange() {
        super.doChange();
        for (int i = 0; i < allDataList.size(); i++) {
            boolean isSelect = false;
            for (int j = 0; j < selectParts.size(); j++) {
                if (allDataList.get(i).getWarehousePartsId().equals(selectParts.get(j).getWarehousePartsId())) {
                    allDataList.get(i).setSelectCount(selectParts.get(j).getSelectCount());
                    adapter.notifyItemChanged(i);
                    isSelect = true;
                    break;
                }
            }
            if (!isSelect) {
                if (allDataList.get(i).getSelectCount() > 0) {
                    allDataList.get(i).setSelectCount(0);
                    adapter.notifyItemChanged(i);
                }
            }
        }
    }

    @Override
    public void sure() {
        super.sure();
        if (selectParts.size() > 0) {
            Intent intent = new Intent();
            intent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) selectParts);
            setResult(RESULT_OK, intent);
            finish();
        } else {
            Toast.makeText(mContext, "您尚未选择任何商品！", Toast.LENGTH_SHORT).show();
        }

    }

    public List<Parts> getSelectParts() {
        return selectParts;
    }

    public void setSelectParts(List<Parts> selectParts) {
        this.selectParts = selectParts;
    }

    private int caculateTotal() {
        int total = 0;
        for (Parts parts : selectParts) {
            total += parts.getSelectCount();
        }
        return total;
    }

    private void openSort() {
        isOpen = true;
        showAnimator.start();
        sortImg.setImageResource(R.mipmap.up);
    }

    private void closeSort() {
        isOpen = false;
        dimissAnimator.start();
        sortImg.setImageResource(R.mipmap.sort_down);
    }

    private ObjectAnimator showAnimator;
    private ObjectAnimator dimissAnimator;

    private void initAnimations() {
        showAnimator = ObjectAnimator.ofFloat(filterGroup, "translationY", UIUtils.dip2px(mContext, 120));
        showAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        showAnimator.setDuration(500);

        dimissAnimator = ObjectAnimator.ofFloat(filterGroup, "translationY", -UIUtils.dip2px(mContext, 120));
        dimissAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        dimissAnimator.setDuration(500);
    }

}
